Skip to content

Optimize ASCII lowercase conversion performance - #15203

Merged
cclauss merged 1 commit into
TheAlgorithms:masterfrom
Miladkhoshdel:perf/optimize-lower
Sep 7, 2026
Merged

Optimize ASCII lowercase conversion performance#15203
cclauss merged 1 commit into
TheAlgorithms:masterfrom
Miladkhoshdel:perf/optimize-lower

Conversation

@Miladkhoshdel

Copy link
Copy Markdown
Contributor

Describe your change:

Improve the performance of the existing ASCII lowercase conversion by replacing the generator expression with an explicit loop.

The updated implementation:

  • Computes each character's ASCII value only once.
  • Uses module-level constants for the ASCII uppercase range and case offset to improve readability and avoid magic numbers.
  • Builds the result using a list and joins it at the end.
  • Preserves the existing behavior and doctests.

Benchmark using:

python -m timeit \
  -s "from strings.lower import lower; s = 'Hello WORLD 123!' * 1000" \
  "lower(s)"

Results on my machine:

  • Previous implementation: ~1.08 ms per loop
  • Updated implementation: ~772 µs per loop
  • Runtime reduction: ~28.5%
  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Add or change doctests? -- Note: Please avoid changing both code and tests in a single pull request.
  • Documentation change?

Checklist:

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All new Python files are placed inside an existing directory.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.
  • All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
  • If this pull request resolves one or more open issues then the description above includes the issue number(s) with a closing keyword: "Fixes #ISSUE-NUMBER".

@algorithms-keeper algorithms-keeper Bot added awaiting reviews This PR is ready to be reviewed enhancement This PR modified some existing files labels Sep 6, 2026

@cclauss cclauss left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a benchmark that proves that the proposed changes provide significant runtime improvements.

@algorithms-keeper algorithms-keeper Bot added awaiting changes A maintainer has requested changes to this PR and removed awaiting reviews This PR is ready to be reviewed labels Sep 6, 2026
@Miladkhoshdel

Copy link
Copy Markdown
Contributor Author

Please add a benchmark that proves that the proposed changes provide significant runtime improvements.

Thanks for the feedback. I benchmarked both implementations under the same conditions using timeit.repeat().

Benchmark code
from statistics import median
from timeit import repeat

ASCII_UPPERCASE_START = ord("A")
ASCII_UPPERCASE_END = ord("Z")
ASCII_CASE_OFFSET = ord("a") - ord("A")


def old_lower(word: str) -> str:
    """
    Will convert the entire string to lowercase letters

    >>> old_lower("wow")
    'wow'
    >>> old_lower("HellZo")
    'hellzo'
    >>> old_lower("WHAT")
    'what'
    >>> old_lower("wh[]32")
    'wh[]32'
    >>> old_lower("whAT")
    'what'
    """

    # Converting to ASCII value, obtaining the integer representation
    # and checking to see if the character is a capital letter.
    # If it is a capital letter, it is shifted by 32, making it a lowercase letter.
    return "".join(chr(ord(char) + 32) if "A" <= char <= "Z" else char for char in word)


def new_lower(word: str) -> str:
    """
    Convert ASCII uppercase letters in a string to lowercase.

    >>> new_lower("wow")
    'wow'
    >>> new_lower("HellZo")
    'hellzo'
    >>> new_lower("WHAT")
    'what'
    >>> new_lower("wh[]32")
    'wh[]32'
    >>> new_lower("whAT")
    'what'
    """
    result = []

    for char in word:
        code = ord(char)
        if ASCII_UPPERCASE_START <= code <= ASCII_UPPERCASE_END:
            char = chr(code + ASCII_CASE_OFFSET)
        result.append(char)

    return "".join(result)


def benchmark(
    text: str,
    number: int = 1_000,
    repeats: int = 10,
) -> None:
    """Benchmark the old and new implementations."""
    assert old_lower(text) == new_lower(text)

    old_times = repeat(
        lambda: old_lower(text),
        number=number,
        repeat=repeats,
    )
    new_times = repeat(
        lambda: new_lower(text),
        number=number,
        repeat=repeats,
    )

    old_min = min(old_times)
    old_median = median(old_times)
    old_max = max(old_times)

    new_min = min(new_times)
    new_median = median(new_times)
    new_max = max(new_times)

    speedup = old_median / new_median
    improvement = (1 - new_median / old_median) * 100

    print(f"Input length: {len(text):,}")
    print(f"Iterations:   {number:,}")
    print(f"Repeats:      {repeats}")
    print()
    print(f"Old: min={old_min:.6f}s, median={old_median:.6f}s, " f"max={old_max:.6f}s")
    print(f"New: min={new_min:.6f}s, median={new_median:.6f}s, " f"max={new_max:.6f}s")
    print()
    print(f"Median speedup:     {speedup:.2f}x")
    print(f"Median improvement: {improvement:.2f}%")
    print("-" * 70)


if __name__ == "__main__":
    sample = "Hello WORLD 123! "

    for multiplier in (10, 100, 1_000, 10_000):
        benchmark(sample * multiplier)

Results:

Input length: 170
Iterations:   1,000
Repeats:      10

Old: min=0.011993s, median=0.012102s, max=0.012210s
New: min=0.008785s, median=0.008824s, max=0.008848s

Median speedup:     1.37x
Median improvement: 27.09%
----------------------------------------------------------------------
Input length: 1,700
Iterations:   1,000
Repeats:      10

Old: min=0.114548s, median=0.115192s, max=0.137890s
New: min=0.083663s, median=0.084050s, max=0.084879s

Median speedup:     1.37x
Median improvement: 27.03%
----------------------------------------------------------------------
Input length: 17,000
Iterations:   1,000
Repeats:      10

Old: min=1.130538s, median=1.133851s, max=1.137077s
New: min=0.809675s, median=0.812048s, max=0.821868s

Median speedup:     1.40x
Median improvement: 28.38%
----------------------------------------------------------------------
Input length: 170,000
Iterations:   1,000
Repeats:      10

Old: min=11.154091s, median=11.242278s, max=11.456039s
New: min=7.952153s, median=7.966990s, max=8.144536s

Median speedup:     1.41x
Median improvement: 29.13%
----------------------------------------------------------------------

Both implementations were tested with the same inputs, iteration counts, and number of repeats. Across the tested input sizes, the proposed implementation shows a consistent median runtime improvement of approximately 27–29%.

@cclauss cclauss left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am a huge believer in comprehensions, but let's go for this anyway.

@algorithms-keeper algorithms-keeper Bot removed the awaiting changes A maintainer has requested changes to this PR label Sep 7, 2026
@cclauss
cclauss merged commit 6328322 into TheAlgorithms:master Sep 7, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement This PR modified some existing files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants